package com.yc.spring.bank.biz;

import com.yc.cinema.biz.BizException;
import com.yc.spring.bank.bean.Account;
import com.yc.spring.bank.bean.Record;
import com.yc.spring.bank.dao.AccountDao;
import com.yc.spring.bank.dao.RecordDaoImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("bankBiz1")
public class BankBizImpl1 implements BankBiz{

    @Resource
    AccountDao accountDao;  // 建议使用接口类型定义变量
    @Resource
    RecordDaoImpl recordDao;  // 不建议使用实现类类型定义变量

    @Override
    public void register(Account account) {

    }

    @Override
    @Transactional
    public void deposit(Integer id, double money) {
        // 省略参数验证
        Account account = accountDao.selectById(id);
        account.setMoney(account.getMoney() + money);
        accountDao.update(account);
        Record record = new Record();
        record.setAccountId(id);
        record.setMoney(money);

        // int i = 1/0;

        recordDao.insert(record);
    }

    @Override
    @Transactional(propagation = Propagation.NEVER)
    public void withdraw(Integer id, double money) throws BizException {
        Account account = accountDao.selectById(id);
        if(account.getMoney() < money){
            throw new BizException("余额不足");
        }
        account.setMoney(account.getMoney() - money);
        accountDao.update(account);
        Record record = new Record();
        record.setAccountId(id);
        record.setMoney(-money);
        recordDao.insert(record);
    }

    @Override
    @Transactional
            //(rollbackFor = BizException.class, noRollbackFor = ArithmeticException.class)
    public void transfer(Integer id1, Integer id2, double money) throws BizException {
        withdraw(id1, money);
        if(money>0){
            // 编译器异常默认不回滚
            // noRollbackFor = 默认情况下 运行时异常默认回滚, 设置不回滚的异常
            // throw new BizException("人为制造的异常!!!");
            // int  i = 1/0;
        }
        deposit(id2,money);
    }

    @Override
    public List<Record> query(Integer id) {
        return null;
    }
}
